# -*- coding: utf-8 -*-
import requests
import json
import sys

requests.packages.urllib3.disable_warnings()

class PowerStoreMonitor:
    def __init__(self, ip, username, password):
        self.base_url = "https://{}/api/rest".format(ip)
        self.username = username
        self.password = password
        self.cookies = self.get_auth_token()

    def get_auth_token(self):
        """获取认证 Cookies"""
        url = "{}/login_session".format(self.base_url)
        response = requests.get(url, auth=(self.username, self.password), verify=False)
        response.raise_for_status()
        return response.cookies


    def fetch_data(self, endpoint, method="GET", params=None, payload=None):
        """通用 API 请求方法"""
        url = "{}/{}".format(self.base_url, endpoint)
        if method == "GET":
            response = requests.get(url, cookies=self.cookies, params=params, verify=False)
        else:
            response = requests.post(url, json=payload, cookies=self.cookies, verify=False)
        response.raise_for_status()
        return response.json()

    def get_all_metrics(self):
        """获取所有监控指标"""
        try:
            data = {
                "capacity": self.fetch_data("storage_container?select=name,quota"),
                "hardware": self.fetch_data("hardware?select=name,type,lifecycle_state")
            }
            return data
        except requests.exceptions.RequestException as e:
            return json.dumps({"error": "API 请求错误: {}".format(e)}, indent=2)

    def get_one_metric(self,type, metric=""):
        data_dict = self.get_all_metrics()
        metric_list=[]
        if type == "capacity":
            print(data_dict[type])
        elif type == "hardware" and metric:
            for item in data_dict[type]:
                if item["type"] == metric:
                    metric_list.append(item)
            print(json.dumps(metric_list))
        else:
            print(json.dumps({"error": "请求错误"}))


if __name__ == "__main__":
    IP = sys.argv[1]
    USER = sys.argv[2]
    PWD = sys.argv[3]
    TYPE = sys.argv[4]
    METRIC = sys.argv[5]
    #10.2.158.156 monitor OPS@2528sjzx
    monitor = PowerStoreMonitor(ip=IP, username=USER, password=PWD)
    monitor.get_one_metric(TYPE,METRIC)